<template>
  <a-card title="添加文章">
    <a-form-model
      :model="form"
      :label-col="labelCol"
      :wrapper-col="wrapperCol"
      :rules="rules"
      ref="ruleForm"
    >
      <a-form-model-item label="文章标题" prop="title">
        <a-input v-model="form.title" />
      </a-form-model-item>
      <a-form-model-item label="文章描述" prop="desc">
        <a-input v-model="form.desc" />
      </a-form-model-item>
      <a-form-model-item label="文章作者">
        <a-input v-model="form.author" type="textarea" />
      </a-form-model-item>
      <a-form-model-item label="封面图片">
        <a-upload
          name="file"
          :multiple="true"
          action="http://rap2api.taobao.org/app/mock/279365/api/v1/upload"
          :headers="headers"
          @change="handleChange"
        >
          <a-button> <a-icon type="upload" />上传图片</a-button>
        </a-upload>
      </a-form-model-item>
      <a-form-model-item label="文章内容">
        <a-input v-model="form.content" type="textarea" />
      </a-form-model-item>
      <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
        <a-button type="primary" @click="onClick"> 提交 </a-button>
      </a-form-model-item>
    </a-form-model>
  </a-card>
</template>
<script>
import { addArt } from '../../../../api'
export default {
  data () {
    return {
      // 表单基本内容
      form: {
        title: '',
        desc: '',
        author: '',
        thumb: '',
        content: ''
      },
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      // 表单规则
      rules: {
        title: [{ required: true, message: '请输入标题' }],
        desc: [{ required: true, message: '请输入描述' }]
      },
      // 设置上传的请求头部，IE10 以上有效
      headers: {
        authorization: 'authorization-text'
      }
    }
  },
  created () {},
  methods: {
    onClick () {
      // console.log(this.form)
      // validate 前面的这个refs里面的ruleForm(指的是a-form-model-item数据)数据如果是真的就执行否则就报错
      this.$refs.ruleForm.validate(v => { // 第一个参数v是布尔值 指的是有验证通过 就执行代码段
        console.log(v)
        if (v) { // 有验证就发送ajax给表单提交
          addArt({ ...this.form }).then(res => {
            if (res.data.code === 200) {
              this.$message.success('提交完成!', 2, () => {
                this.$router.go(0)
              })
            }
          })
        } else { // 没有就报错
          console.log('提交错误!')
          return false
        }
      })
    },
    handleChange (res) {
      // console.log(res)
      if (res.file.status !== 'uploading') {
        console.log(res.file, res.fileList)
      }
      if (res.file.status === 'done') {
        this.form.thumb = res.file.name
        this.$message.success(`${res.file.name} '上传成功'`)
      } else if (res.file.status === 'error') {
        this.$message.error(`${res.file.name} '上传失败'`)
      }
    }
  }
}
</script>

<style lang='scss' scoped>
</style>
